home *** CD-ROM | disk | FTP | other *** search
- Path: news.sinet.slb.com!usenet
- From: "Vinh D. Nguyen" <vnguyen@sugar-land.anadrill.slb.com>
- Newsgroups: comp.lang.c++
- Subject: Re: Dynamic alloc of 2D array??
- Date: Tue, 12 Mar 1996 08:29:52 -0600
- Organization: Schlumberger Anadrill
- Message-ID: <31458A60.17E0@sugar-land.anadrill.slb.com>
- References: <4hpjbo$fsb@masala.cc.uh.edu>
- NNTP-Posting-Host: 163.185.118.40
- Mime-Version: 1.0
- Content-Type: text/plain; charset=us-ascii
- Content-Transfer-Encoding: 7bit
- X-Mailer: Mozilla 2.0 (WinNT; I)
-
- sukumar wrote:
- > char** cities;
- >
- > // Alloc x number of char*s
- > cities = new (char* [x]);
- >
- > for(i=0; i<x; i++)
- > delete [] cities[i];
- > delete [] cities;
- >
- > The program crashes when I don't assign anything to the cities.
- > What is the right way to alloc an array of pointers and delete them??
- >
- > TIA,
- > SK
-
- Your program crashed because you did not initialize the cities array to NULL.
- Objects (variables, arrays, etc.) in C and C++ are on initialized upon creation,
- so without initialization, your cities array contain garbage values. When you attempt
- to destroy the entries in cities, you are trying to deallocate memory pointed at
- by these garbage values. The correct way to avoid this problem is to initialize cities
- to NULL as follows:
-
- cities = new char * [ x ];
- memset( cities, 0, x * sizeof( char * ) );
-
- The delete operator becomes a no-op when operated on a NULL pointer.
-
- Hope this helps.
-
- --
- --------------------------------------------------------------------------
- * Vinh Nguyen vnguyen@slb.com *
- * Drilling Information Products - Senior Engineer *
- * Anadrill Schlumberger *
- * 200 Gillingham Ln. (713) 275-7524 (Office) *
- * Sugarland, TX 77478 (713) 275-8098 (FAX) *
- --------------------------------------------------------------------------
-